
$("[name=fwcode]").mask('9999-9999-9999-9999', {'completed': function(){
    // console.info(this.val())
    $('#postfwcodebtn').removeClass('weui_btn_disabled')
}})


//自动加载防伪码
$(document).ready(function(){
    var fwcode = location.search.match(/qrcode=(\d{16})/)
    if(fwcode){
        fwcode = fwcode[1]
        var value = ''
        for(var i=0;i<12;i+=4){
            value += fwcode.slice(i, i+4) + '-'
        }
        value += fwcode.slice(i, i+4)
        $("[name=fwcode]").val(value)
        $('#postfwcodebtn').removeClass('weui_btn_disabled')
    }
})
//二维码扫描
$(document).on('click', '#fwscan:not(.weui_btn_disabled)', function(){
    wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: fwscansucfunc
    });
})
fwscansucfunc = function(res){
    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
    var codes = result.split('http://wap.xologood-fc.com/yingbaozhineng/fw.html?code=')
    if(codes.length!=2){
        mymessage('二维码有误')
    }else{
        var code = codes[1]
        var newfwvalue = ''
        var i
        for(i=0;i<3;i++){
            newfwvalue += code.slice(i*4, i*4+4) + '-'
        }
        newfwvalue += code.slice(i*4, i*4+4)
        $('[name=fwcode]').val(newfwvalue)
        $('#postfwcodebtn').removeClass('weui_btn_disabled')
    }    
}
//微信js绑定
if($(document).find('.wx_data').length==1){
    var wxconfig = {}
    $('.wx_data input').each(function(i, e){
        wxconfig[e.name] = e.value;
    })    
    wxconfig.debug = false; //debug 开关
    wxconfig.jsApiList = [
        'checkJsApi', 'chooseImage', 'uploadImage', 'hideMenuItems', 
        'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ',
        'onMenuShareWeibo', 'onMenuShareQZone', 'previewImage', 'scanQRCode',
    ];
    wx.config(wxconfig);
    wx.ready(function(){
        wx.checkJsApi({
            jsApiList: ['chooseImage', 'uploadImage', 'scanQRCode'],
            success: function(res){               
                $('#fwscan').removeClass('weui_btn_disabled');
            },
        });
    });    
}


$(document).on('click', '#postfwcodebtn:not(.weui_btn_disabled)', function(){
    // console.info(code)
    var self = $(this)
    var code = $('[name=fwcode]').val().replace(/-/g, '')
    if(code.length!=16){
        mymessage('输入不全')
        $('#fwcode').focus()
        return false;
    }
    myloadingshow('提交中...')
    self.addClass('weui_btn_disabled')
    $.post('manage?action=selladdproduct&fwcode=' + code, null, null, 'json').done(function(data){
        // console.info(data)
        $('.mylist tbody').prepend('<tr><td>'+ data.pname 
            + '</td><td>'+data.ctime
            +'</td><td>'+data.reward 
            + '</td><td><i class="weui_icon_waiting"></i></td>')
        var total = parseInt($('#totalreward').text())
        $('#totalreward').text(total+data.reward)
        myloadinghide()
        self.removeClass('weui_btn_disabled')
        mymessage_suc('添加成功');            
    }).fail(function(data){
        // console.info(data)
        data = data.responseText
        myloadinghide()
        self.removeClass('weui_btn_disabled')        
        if(data=='alreadyget'||data=='saveAleadyError'){
            mymessage('防伪码重复');
        }else if(data=='fwcodenotfetch'){
            // mymessage('防伪码错误');
            var sucf = function(){
                location.href = 'sellverify?fwcode='+code;
            }
            var content = '<div style="text-align:center"><i class="weui_icon_msg weui_icon_warn"></i><br>提交的产品防伪码有误<br>点击确定进入校验页面</div>'
            dialog1('防伪码错误', content, sucf)
        }else if(data=='notagmsell'){
            mymessage('非销售用户');             
        }else{
            mymessage(data);
        }
    })
    
})

//加载Toast
myloadingshow = function(title){
    var toast = $('#loadingToast')
    toast.find('.weui_toast_content').text(title)
    toast.show()
}
myloadinghide = function(){$('#loadingToast').hide()}
mymessage = function(content){
    var toast = $('#toast')
    toast.find('.weui_toast_content').text(content)
    toast.find('i').attr('class', 'weui_icon_toast_info')
    toast.show()
    setTimeout("$('#toast').hide()", 1500);
}
mymessage_suc = function(content){
    var toast = $('#toast')
    toast.find('.weui_toast_content').text(content)
    toast.find('i').attr('class', 'weui_icon_toast')
    toast.show()
    setTimeout("$('#toast').hide()", 1500);    
}

//显示扫码提示页面开关
if(document.cookie.search('role=agmsell')!=-1){
    $('#showfwchoie')[0].checked = true
}
$('#showfwchoie').click(function(){
    console.info(this.checked)
    setsellcookie(this.checked)
})
//设置role=agmsell的cookie
setsellcookie = function(v){
    if(v){
        var d = new Date();
        d.setTime(d.getTime() + (30*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = "role=agmsell; " + expires;
    }else{
        document.cookie = "role=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    }
}
//弹出信息对话框
dialog1= function(title, content, sucfunc){
    var dailog = $('#dialog1')
    dailog.find('.weui_dialog_title').text(title)
    dailog.find('.weui_dialog_bd').html(content)
    dailog.find('.weui_btn_dialog.default').click(function(){
        dailog.hide()
    })
    dailog.find('.weui_btn_dialog.primary').unbind('click').click(sucfunc)        
    dailog.show()
}
dialog2 = function(title, content, sucfunc){
    var self = $('#dialog2')
    self.find('.weui_dialog_title').text(title)
    self.find('.weui_dialog_bd').html(content)
    var clickfunc = sucfunc?sucfunc:function(){self.hide();}
    self.find('.weui_btn_dialog.primary').one('click', clickfunc)
    self.show()
}
//点击活动支付查看详情
$('td[dtime]').css('cursor','pointer')
$(document).on('click', 'td[dtime]', function(){
    var self = $(this)
    var content = '<div style="text-align:left;color:black">'
    var dtags = [['dpid', '类型编号'], ['dcost', '交易金额(元)'], ['dtime', '支付时间'], ['dtid', '交易单号'], ['doid', '商户订单号'], ['dreward', '奖励金额'],['drtime', '奖励时间']]
    for(i in dtags){
        content += '<div class="weui_cells_title">'+dtags[i][1]+'</div><div class="weui_cells"><div class="weui_cell"><div class="weui_cell_bd weui_cell_primary"><p>'+self.attr(dtags[i][0])+'</p></div></div></div>'
    }
    content += '</div>'
    // console.info(content)
    dialog2('订单详情', content)
})
//搜索键绑定系列
$('#search_input').blur(function(){
    if(!this.value){
        $('#search_bar').removeClass('weui_search_focusing')
    }
}).bind('input', function(){
    var value = this.value
    if(value){
        $('.mylist tbody tr').each(function(){
           var self = $(this)
           var td = self.find('td[dtid]')
           if(td.attr('dtid').search(value)==-1 && td.attr('dpid').search(value)==-1){
                self.hide()
           }else{
                self.show()
           }
        })
    }else{
        $('.mylist tbody tr').show()
    }
}).focus(function(){
    $('#search_bar').addClass('weui_search_focusing')
})
$('#search_clear').click(function(){
    $('#search_input').val("").focus()
    $('.mylist tbody tr').show()
})
$('#search_cancel').click(function(){
    $('#search_input').val("")
    $('.mylist tbody tr').show()
    $('#search_bar').removeClass('weui_search_focusing')
})

//后台查询订单键绑定
$('#search_other').click(function(){
    var content = '<div class="weui_cells"><div class="weui_cell weui_cell_select"><div class="weui_cell_bd weui_cell_primary"><select class="weui_select" name="idtype"><option selected="" value="1">交易单号</option><option value="2">商户单号</option></select></div></div><div class="weui_cell"><div class="weui_cell_bd weui_cell_primary"><input id="tid" class="weui_input" type="number" pattern="[0-9]*" placeholder="请输入交易单号或商户单号"></div></div></div>'
    var foot = '注意:通过本对话框进行微信支付后台查询，一般用于顾客支付后于清单中无显示下使用。'
    content += '<div class="weui_cells_tips">' + foot +'</div>'
    sucfunc = function(){
        $('#dialog1').hide()
        myloadingshow('查询中...')
        var idtype = $('[name=idtype]').val()
        var id = $('#tid').val()
        $.post('?tid='+id+'&idtype='+idtype, function(data){
            myloadinghide()
            console.info(data)
            if(data=='success_add'||data=='success'){
                mymessage_suc('订单支付成功，自动刷新本页')
                location.reload()
            }else{
                mymessage(data)
            }
        })
    }
    dialog1('订单后台查询确认', content, sucfunc)
})
//刷新本页绑定
$('#refresh').click(function(){location.reload()})